package com.chapter1.basic.stack;

import java.util.Iterator;

/** 
 * @ClassName: FixCapacityStack 
 * @Description: 自定义固定容量栈
 * @author minjun minjun@bw30.com
 * @date 2015-2-11 下午10:37:18 
 *  
 */
@SuppressWarnings("unchecked")
public class AutoResizeStack<Item> implements Iterable<Item>{
	
	private Item[] items;
	
	private int capacity=5;
	
	private int index=0;
	
	public AutoResizeStack() {
		items=(Item[]) new Object[capacity];
	}

	public void push(Item item){
		if(index>capacity-1){
			resize(capacity<<1);
		}
		items[index++]=item;
	}
	
	public Item pop(){
		if(index==0){
			return null;
		}else{
			Item item=items[--index];
			items[index]=null;
			if(index<=capacity/4){
				resize(capacity>>1);
			}
			return item;
		}
	}
	
	/** 
	* @Title: resize 
	* @Description: 自动扩容
	* @param     设定文件 
	* @return void    返回类型 
	* @throws 
	*/ 
	private void resize(int capacity) {
		Item[] newItems=(Item[]) new Object[capacity];
		for(int i=0;i<index;i++){
			newItems[i]=items[i];
		}
		this.capacity=capacity;
		items=newItems;
	}
	
	public int size(){
		return capacity;
	}

	@Override
	public Iterator<Item> iterator() {
		return new MyStackIterator();
	}
	
	/** 
	 * @ClassName: MyStackIterator 
	 * @Description:内部类迭代器(由于需要获取被迭代的对象容器，所以放到内部类可以方便的直接获取容器对象) 
	 * @author minjun minjun@bw30.com
	 * @date 2015-2-11 下午11:51:17 
	 *  
	 */
	public class MyStackIterator implements Iterator<Item>{
		
		/**
		 * 保存一份index位置，以改变了容器本身的index位置
		 */
		private int i=index;

		@Override
		public boolean hasNext() {
			return i>0;
		}

		@Override
		public Item next() {
			if(!hasNext()){
				throw new RuntimeException("没有元素了");
			}
			return items[--i];
		}

		@Override
		public void remove() {
			
		}

	}

}
